package com.bw.zg3_day05zy

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil.ItemCallback
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.bw.base.entity.NoticeBeanItem
import com.bw.zg3_day05zy.databinding.ItemNoticeBinding

class NoticeAdapter: PagingDataAdapter<NoticeBeanItem, NoticeAdapter.NoticeViewHolder>(diff) {
    private var mOnItemClickListener: OnItemClickListener? = null
    private var mOnItemLongClickListener: OnItemLongClickListener? = null
    companion object{
        val diff = object : ItemCallback<NoticeBeanItem>(){
            override fun areItemsTheSame(
                oldItem: NoticeBeanItem,
                newItem: NoticeBeanItem
            ): Boolean {
                return oldItem == newItem
            }

            override fun areContentsTheSame(
                oldItem: NoticeBeanItem,
                newItem: NoticeBeanItem
            ): Boolean {
                return oldItem.id == newItem.id
            }
        }
    }
    class NoticeViewHolder(view: View): ViewHolder(view) {
        val binding = DataBindingUtil.bind<ItemNoticeBinding>(view)
    }

    override fun onBindViewHolder(holder: NoticeViewHolder, position: Int) {
        val item = getItem(position)
        holder.binding?.bean = item
        holder.itemView.setOnClickListener {
            this.mOnItemClickListener?.onItemClick(item!!,position)
        }
        holder.itemView.setOnLongClickListener {
            this.mOnItemLongClickListener?.onItemLongClick(item!!)
            return@setOnLongClickListener true
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoticeViewHolder {
        val view =
            LayoutInflater.from(parent.context).inflate(R.layout.item_notice, parent, false)
        return NoticeViewHolder(view)
    }

    fun setOnItemClickListener(listener: OnItemClickListener?) {
        this.mOnItemClickListener = listener
    }

    fun setOnItemLongClickListener(listener: OnItemLongClickListener?) {
        this.mOnItemLongClickListener = listener
    }

    interface OnItemClickListener {
        fun onItemClick(item: NoticeBeanItem, position: Int)
    }

    interface OnItemLongClickListener {
        fun onItemLongClick(item: NoticeBeanItem): Boolean
    }
}